﻿using libzkfpcsharp;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using wareHouse;

namespace ShuoXiangProductionPlatform
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
            StartPosition = FormStartPosition.CenterScreen;
            this.FormBorderStyle = FormBorderStyle.None;
            FormHandle = this.Handle;
            //指纹识别模块初始化，暂时注释不用
            //InitFingerprint();
            login = this;
           
            this.groupBox1.Hide();
            this.cmbIdx.Hide();
        }

        /// <summary>
        /// 指纹识别模块初始化
        /// </summary>
        public void InitFingerprint()
        {
            int ret = zkfperrdef.ZKFP_ERR_OK;
            if ((ret = zkfp2.Init()) == zkfperrdef.ZKFP_ERR_OK)
            {
                int nCount = zkfp2.GetDeviceCount();
                if (nCount > 0)
                {
                    for (int i = 0; i < nCount; i++)
                    {
                        cmbIdx.Items.Add(i.ToString());
                    }
                    cmbIdx.SelectedIndex = 0;

                }
                Console.WriteLine("指纹识别连接成功");
            }
            else
            {
                MessageBox.Show("Initialize fail, ret=" + ret + " !");
            }

        }

        public static Login login = null;
        public static ProduceSystem produceSystem = new ProduceSystem();

        /// <summary>
        /// 存储账户信息
        /// </summary>
        private Dictionary<string, UserInfo> Userinfo = new Dictionary<string, UserInfo>();

        /// <summary>
        /// 存储已录入的指纹信息，程序关闭时暂时写入本地
        /// </summary>
        public Dictionary<int, byte[]> fingerprintinfo = new Dictionary<int, byte[]>();

        /// <summary>
        /// 登陆的账户信息
        /// </summary>
        public UserInfo userInfo = new UserInfo();

        /// <summary>
        /// 登陆模式，0：账号密码登陆；1：指纹登陆
        /// </summary>
        private static int loginmode = 0;

        private static string key = "suxiang__gnaixus";
        bool bIdentify = true;

        //指纹识别部分初始化
        IntPtr mDevHandle = IntPtr.Zero;
        IntPtr mDBHandle = IntPtr.Zero;
        IntPtr FormHandle = IntPtr.Zero;
        bool bIsTimeToDie = false;
        public bool IsRegister = false;
        byte[] FPBuffer;
        int RegisterCount = 0;
        const int REGISTER_FINGER_COUNT = 3;

        byte[][] RegTmps = new byte[3][];
        byte[] RegTmp = new byte[2048];
        byte[] CapTmp = new byte[2048];
        int cbCapTmp = 2048;
        int cbRegTmp = 2018;
        int iFid = 1;
        private int mfpWidth = 0;
        private int mfpHeight = 0;

        const int MESSAGE_CAPTURED_OK = 0x0400 + 6;
        [DllImport("user32.dll", EntryPoint = "SendMessageA")]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

        private void button1_Click(object sender, EventArgs e)
        {

            try
            {
                //string param = "{\"account\":\"textzdzd\",\"password\":\"123456\",\"deviceId\":\"863576926784880\"}";
                //获取输入的账户密码
                LoginInfo loginInfo = new LoginInfo();
                loginInfo.account = textBox1.Text;
                loginInfo.password = textBox2.Text;
                loginInfo.deviceId = "863576926784880";
                //调用登陆接口，获取返回数据
                string param = JsonConvert.SerializeObject(loginInfo);
                HttpHelper httpHelper = new HttpHelper();
                string res = httpHelper.HTTPJsonPost("http://47.102.195.242:28083/user/login/p", param);
                //反序列化
                var resjson = JsonConvert.DeserializeObject<JsonString.ApiMsg<JsonString.logindata>>(res);
                //返回数据中包含T，表示登陆成功
                if (resjson.success.Equals("T"))
                {
                    userInfo.account = this.textBox1.Text;
                    userInfo.password = this.textBox2.Text;
                    userInfo.logindata = resjson.data;
                    this.groupBox1.Show();
                    this.pictureBox4.Image = Image.FromFile(Application.StartupPath + "\\img\\完成.png");
                    this.label4.Text = resjson.msg;
                    timer2.Enabled = true;
                    timer2.Interval = 1000;
                    timer2.Tick += Timer2_Tick;
                }
                else
                {
                    this.pictureBox4.Image = Image.FromFile(Application.StartupPath + "\\img\\failue.png");
                    this.label4.Text = resjson.msg;
                    this.groupBox1.Show();
                    timer1.Enabled = true;
                    timer1.Interval = 1000 * 2;
                    timer1.Tick += Timer1_Tick;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("登陆失败", ex);
                MessageBox.Show("登陆失败，请重试");
            }

            #region 测试用例 已废弃
            ////如果存在用户名则开始对比用户名密码是否正确
            //if (Userinfo.Keys.Contains(this.textBox1.Text))
            //{
            //    Userinfo.TryGetValue(this.textBox1.Text, out var userinfo);
            //    var password = StaticHelper.AesEncrypt(this.textBox2.Text, key);
            //    //密码一致登录成功
            //    if (password == userinfo.password)
            //    {
            //        //this.WindowState = FormWindowState.Minimized;
            //        //this.ShowInTaskbar = false;
            //        //记录当前账户信息
            //        userInfo.account = this.textBox1.Text;
            //        userInfo.password = this.textBox2.Text;
            //        this.groupBox1.Show();
            //        this.pictureBox4.Image = Image.FromFile(Application.StartupPath + "\\img\\完成.png");
            //        this.label4.Text = "登陆成功";
            //        timer2.Enabled = true;
            //        timer2.Interval = 1000;
            //        timer2.Tick += Timer2_Tick;

            //    }
            //    else
            //    {
            //        this.pictureBox4.Image = Image.FromFile(Application.StartupPath + "\\img\\failue.png");
            //        this.label4.Text = "账户或密码不正确";
            //        this.groupBox1.Show();
            //        timer1.Enabled = true;
            //        timer1.Interval = 1000 * 2;
            //        timer1.Tick += Timer1_Tick;
            //    }
            //}
            //else
            //{
            //    this.pictureBox4.Image = Image.FromFile(Application.StartupPath + "\\img\\failue.png");
            //    this.label4.Text = "账户或密码不正确";
            //    this.groupBox1.Show();
            //    timer1.Enabled = true;
            //    timer1.Interval = 1000 * 2;
            //    timer1.Tick += Timer1_Tick;

            //}
            #endregion
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            this.groupBox1.Hide();

            timer1.Enabled = false;
        }

        private void Timer2_Tick(object sender, EventArgs e)
        {
            //main.Visible = false;
            this.pictureBox1.Image = Image.FromFile(Application.StartupPath + "\\img\\指纹登录.png");
            this.label5.Text = "指纹登陆";
            loginmode = 0;
            //登录成功，显示主页面
            //main.Show();
            produceSystem.Show();

            produceSystem.label3.Text = "欢迎" + userInfo.logindata.name;
            LogHelper.WriteLog("用户" + userInfo.logindata.name + "登陆系统成功");
            this.groupBox1.Hide();
            login.Hide();
            this.textBox2.Text = "";
            timer2.Enabled = false;
        }


        private void Timer3_Tick(object sender, EventArgs e)
        {
            this.groupBox1.Hide();
            this.timer3.Enabled = false;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            if (loginmode == 0)
            {
                this.pictureBox1.Image = Image.FromFile(Application.StartupPath + "\\img\\账号管理.png");
                this.label5.Text = "账号登陆";
                OpenFingerprint();
                bIdentify = true;
                loginmode = 1;
            }
            else
            {
                this.pictureBox1.Image = Image.FromFile(Application.StartupPath + "\\img\\指纹登录.png");
                this.label5.Text = "指纹登陆";
                bIdentify = false;
                //zkfp2.CloseDevice(mDevHandle);
                loginmode = 0;
            }
        }


        /// <summary>
        /// 打开指纹识别设备
        /// </summary>
        public void OpenFingerprint()
        {
            int ret = zkfp.ZKFP_ERR_OK;
            if (IntPtr.Zero == (mDevHandle = zkfp2.OpenDevice(cmbIdx.SelectedIndex)))
            {
                MessageBox.Show("OpenDevice fail");
                return;
            }
            if (IntPtr.Zero == (mDBHandle = zkfp2.DBInit()))
            {
                MessageBox.Show("Init DB fail");
                zkfp2.CloseDevice(mDevHandle);
                mDevHandle = IntPtr.Zero;
                return;
            }
            RegisterCount = 0;
            //cbRegTmp = 0;

            for (int i = 0; i < 3; i++)
            {
                RegTmps[i] = new byte[2048];
            }
            byte[] paramValue = new byte[4];
            int size = 4;
            zkfp2.GetParameters(mDevHandle, 1, paramValue, ref size);
            zkfp2.ByteArray2Int(paramValue, ref mfpWidth);

            size = 4;
            zkfp2.GetParameters(mDevHandle, 2, paramValue, ref size);
            zkfp2.ByteArray2Int(paramValue, ref mfpHeight);

            FPBuffer = new byte[mfpWidth * mfpHeight];

            Thread captureThread = new Thread(new ThreadStart(DoCapture));
            captureThread.IsBackground = true;
            captureThread.Start();
            bIsTimeToDie = false;
            //var str = File.ReadAllText("C:\\Users\\87959\\source\\repos\\test\\test\\bin\\Debug\\test.txt");
            //var bytes = StaticHelper.strToToHexByte(str);
            //if (zkfp.ZKFP_ERR_OK == zkfp2.DBAdd(mDBHandle, 1, bytes))
            //{

            //    cbRegTmp = 2018;
            //}

        }


        private void DoCapture()
        {
            while (!bIsTimeToDie)
            {
                cbCapTmp = 2048;
                int ret = zkfp2.AcquireFingerprint(mDevHandle, FPBuffer, CapTmp, ref cbCapTmp);
                if (ret == zkfp.ZKFP_ERR_OK)
                {
                    var a = SendMessage(FormHandle, MESSAGE_CAPTURED_OK, IntPtr.Zero, IntPtr.Zero);
                }
                Thread.Sleep(200);
            }
        }

        protected override void DefWndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case MESSAGE_CAPTURED_OK:
                    {

                        if (IsRegister)
                        {
                            //if (userInfo.Fid != 0)
                            //{
                            //    FingerprintManagement.fingerprintManagement.groupBox1.Show();
                            //    FingerprintManagement.fingerprintManagement.pictureBox2.Image = Image.FromFile(Application.StartupPath + "\\img\\提示 (2).png");
                            //    FingerprintManagement.fingerprintManagement.label2.Text = "您已录入指纹信息，如需修改请联系管理员";
                            //    FingerprintManagement.fingerprintManagement.timer1.Enabled = true;
                            //    FingerprintManagement.fingerprintManagement.timer1.Interval = 1500;
                            //    FingerprintManagement.fingerprintManagement.timer1.Tick += Timer1_Tick1;
                            //    IsRegister = false;
                            //    return;
                            //}
                            //int ret = zkfp.ZKFP_ERR_OK;
                            //int fid = 0, score = 0;
                            //ret = zkfp2.DBIdentify(mDBHandle, CapTmp, ref fid, ref score);
                            //if (zkfp.ZKFP_ERR_OK == ret)
                            //{
                            //    //textRes.Text = "This finger was already register by " + fid + "!";
                            //    FingerprintManagement.fingerprintManagement.groupBox1.Show();
                            //    FingerprintManagement.fingerprintManagement.pictureBox2.Image = Image.FromFile(Application.StartupPath + "\\img\\提示 (2).png");
                            //    FingerprintManagement.fingerprintManagement.label2.Text = "指纹已存在如需修改请联系管理员";
                            //    FingerprintManagement.fingerprintManagement.timer1.Enabled = true;
                            //    FingerprintManagement.fingerprintManagement.timer1.Interval = 1500;
                            //    FingerprintManagement.fingerprintManagement.timer1.Tick += Timer1_Tick1;
                            //    IsRegister = false;
                            //    //zkfp2.CloseDevice(mDevHandle);
                            //    return;
                            //}
                            //if (RegisterCount > 0 && zkfp2.DBMatch(mDBHandle, CapTmp, RegTmps[RegisterCount - 1]) <= 0)
                            //{
                            //    //textRes.Text = "Please press the same finger 3 times for the enrollment";
                            //    FingerprintManagement.fingerprintManagement.groupBox1.Show();
                            //    FingerprintManagement.fingerprintManagement.pictureBox2.Image = Image.FromFile(Application.StartupPath + "\\img\\提示 (2).png");
                            //    FingerprintManagement.fingerprintManagement.label2.Text = "请使用同一个手指进行指纹录入";
                            //    FingerprintManagement.fingerprintManagement.timer1.Enabled = true;
                            //    FingerprintManagement.fingerprintManagement.timer1.Interval = 1500;
                            //    FingerprintManagement.fingerprintManagement.timer1.Tick += Timer1_Tick1;
                            //    IsRegister = false;
                            //    return;
                            //}
                            //Array.Copy(CapTmp, RegTmps[RegisterCount], cbCapTmp);
                            //String strBase64 = zkfp2.BlobToBase64(CapTmp, cbCapTmp);
                            //byte[] blob = zkfp2.Base64ToBlob(strBase64);
                            //RegisterCount++;
                            //if (RegisterCount >= REGISTER_FINGER_COUNT)
                            //{
                            //    RegisterCount = 0;
                            //    if (zkfp.ZKFP_ERR_OK == (ret = zkfp2.DBMerge(mDBHandle, RegTmps[0], RegTmps[1], RegTmps[2], RegTmp, ref cbRegTmp)) &&
                            //           zkfp.ZKFP_ERR_OK == (ret = zkfp2.DBAdd(mDBHandle, iFid, RegTmp)))
                            //    {
                            //        userInfo.Fid = iFid;
                            //        iFid++;
                            //        var RegTmpstr = StaticHelper.byteToHexStr(RegTmp);
                            //        //File.WriteAllText("C:\\Users\\87959\\source\\repos\\test\\test\\bin\\Debug\\test.txt", RegTmpstr);
                            //        //textRes.Text = "enroll succ";
                            //        FingerprintManagement.fingerprintManagement.groupBox1.Show();
                            //        FingerprintManagement.fingerprintManagement.timer1.Enabled = true;
                            //        FingerprintManagement.fingerprintManagement.timer1.Interval = 1000;
                            //        FingerprintManagement.fingerprintManagement.timer1.Tick += Timer1_Tick1;
                            //    }
                            //    else
                            //    {
                            //        //textRes.Text = "enroll fail, error code=" + ret;
                            //    }
                            //    //zkfp2.CloseDevice(mDevHandle);
                            //    IsRegister = false;
                            //    return;
                            //}
                            //else
                            //{
                            //    main.fingerprintManagement.label1.Text = "需要验证" + (REGISTER_FINGER_COUNT - RegisterCount) + "次指纹";
                            //    //textRes.Text = "You need to press the " + (REGISTER_FINGER_COUNT - RegisterCount) + " times fingerprint";
                            //}
                        }
                        else
                        {
                            if (cbRegTmp <= 0)
                            {
                                //textRes.Text = "Please register your finger first!";
                                this.pictureBox4.Image = Image.FromFile(Application.StartupPath + "\\img\\failue.png");
                                this.groupBox1.Show();
                                this.label4.Text = "无法识别";
                                timer2.Enabled = true;
                                timer2.Interval = 1500;
                                timer2.Tick += Timer1_Tick;

                                return;
                            }
                            if (bIdentify)
                            {
                                int ret = zkfp.ZKFP_ERR_OK;
                                int fid = 0, score = 0;
                                ret = zkfp2.DBIdentify(mDBHandle, CapTmp, ref fid, ref score);
                                if (zkfp.ZKFP_ERR_OK == ret)
                                {
                                    //textRes.Text = "Identify succ, fid= " + fid + ",score=" + score + "!";
                                    //MessageBox.Show("Identify succ, fid= " + fid + ",score=" + score + "!");
                                    userInfo.Fid = fid;
                                    this.groupBox1.Show();
                                    this.pictureBox4.Image = Image.FromFile(Application.StartupPath + "\\img\\完成.png");
                                    this.label4.Text = "登陆成功";
                                    timer2.Enabled = true;
                                    timer2.Interval = 1000;
                                    timer2.Tick += Timer2_Tick;
                                    bIdentify = false;
                                    return;
                                }
                                else
                                {
                                    //textRes.Text = "Identify fail, ret= " + ret;
                                    this.groupBox1.Show();
                                    this.pictureBox4.Image = Image.FromFile(Application.StartupPath + "\\img\\failue.png");
                                    this.label4.Text = "验证失败";
                                    timer3.Enabled = true;
                                    timer3.Interval = 1000;
                                    timer3.Tick += Timer3_Tick;
                                    return;
                                }
                            }
                            else
                            {
                                int ret = zkfp2.DBMatch(mDBHandle, CapTmp, RegTmp);
                                if (0 < ret)
                                {
                                    //textRes.Text = "Match finger succ, score=" + ret + "!";
                                    return;
                                }
                                else
                                {
                                    //textRes.Text = "Match finger fail, ret= " + ret;
                                    return;
                                }
                            }
                        }
                    }
                    break;

                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }

        private void pictureBox3_Click(object sender, EventArgs e)
        {
            LogHelper.WriteLog("用户" + userInfo.logindata.name + "退出系统");
            this.Close();
        }
    }
}
